package com.zou.lotterylucky.activity

import android.app.DatePickerDialog
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.elvishew.xlog.XLog
import com.google.zxing.integration.android.IntentIntegrator
import com.jakewharton.rxbinding3.view.clicks
import com.kaopiz.kprogresshud.KProgressHUD
import com.v2.request.RequestCenter
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.Constants
import com.zou.lotterylucky.R
import com.zou.lotterylucky.data.Order
import com.zou.lotterylucky.utils.*
import kotlinx.android.synthetic.main.activity_check.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit

class RedeemActivity : BaseActivity() {
    private lateinit var adapter: DealsAdapter
    private var ordersData: MutableList<Order> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_redeem)

        topbar.setTitle(R.string.redeem)
        topbar.addLeftBackImageButton().setOnClickListener { onBackPressed() }

        searchBtn.setOnClickListener {
            loadOrders()
        }

        scanBtn.setOnClickListener {
            IntentIntegrator(this)
                .setDesiredBarcodeFormats(IntentIntegrator.QR_CODE).initiateScan()
        }

        adapter =
            DealsAdapter(ordersData)
        rcv.layoutManager = LinearLayoutManager(this)
        rcv.adapter = adapter

        adapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this, OrderDetailActivity::class.java)
            selectedOrder = adapter.data[position]
            intent.putExtra("from", 0)
            startActivity(intent)
        }

        AidlUtil.instance.getTime("yyyy-MM-dd", object : TimeCallBack {
            override fun onError(msg: String?) {

            }

            override fun onSuccess(time: String?) {

                val dateFormatter = SimpleDateFormat("yyyy-MM-dd")
                val date = dateFormatter.parse(time)
                var cal = Calendar.getInstance()
                cal.time = date
                cal.add(Calendar.DATE, -1)
                val resultTime = dateFormatter.format(cal.time)
                tv_time_start.text = resultTime
                tv_time_end.text = resultTime
            }
        })

        val dateFormatter = SimpleDateFormat("yyyy-MM-dd")
        var cal = Calendar.getInstance()
        val dateSetListener =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                tv_time_start.text = dateFormatter.format(cal.time)
            }

        tv_time_start.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                DatePickerDialog(
                    this, dateSetListener,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)
                ).show()
            }

        val dateSetListener1 =
            DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                cal.set(Calendar.YEAR, year)
                cal.set(Calendar.MONTH, monthOfYear)
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
                tv_time_end.text = dateFormatter.format(cal.time)
            }

        tv_time_end.clicks().throttleFirst(1000, TimeUnit.MILLISECONDS)
            .subscribe {
                DatePickerDialog(
                    this, dateSetListener1,
                    cal.get(Calendar.YEAR),
                    cal.get(Calendar.MONTH),
                    cal.get(Calendar.DAY_OF_MONTH)
                ).show()
            }

        loadOrders()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)

        if (result != null) {
            val str = result.contents
            XLog.e(str)
            try {
                val jsonBean = JSONObject(str)
                val number = jsonBean.getString("or")
                val machineNumber = SPUtils[this, "username", "0001"] as String
                val jihao = number.substring(0, machineNumber.length)
                if (jihao != machineNumber) {
                    ToastUtil.showMsg(this, "机号不符")
                    return
                }
                loadOrderByNumer(number)
//                selectedOrder = allOrders.find { it -> it.serialNumber == number }!!
//                val intent = Intent(this, OrderDetailActivity::class.java)
//                intent.putExtra("from", 1)
//                startActivity(intent)
            } catch (e: Exception) {
                XLog.e(e)
                ToastUtil.showTipsError(this, getString(R.string.error_qr))
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    private fun loadOrders() {
        val requestQueue = Volley.newRequestQueue(this)

        val url = Constants.SERVER_URL + "getOrders"
        val params = JSONObject()
        params.put("machine_number", SPUtils[this, "username", ""])
        if (!orderNumberTxt.text.isNullOrBlank()) {
            params.put("number", orderNumberTxt.text)
        }
        val startTimeStr = tv_time_start.text.toString() + " " + "00:00:00"
        val startTimeDate = DateUtil.localToUTC(startTimeStr)
        val endTimeStr = tv_time_end.text.toString() + " " + "23:59:59"
        val endTimeDate = DateUtil.localToUTC(endTimeStr)
        params.put("start", SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(startTimeDate))
        params.put("end", SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(endTimeDate))
        params.put("iswinner", "0")
        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
            try {

                val status = response.get("status") as Int
                if (status == 200 && !response.isNull("data")) {

                    val data = response.get("data") as JSONArray

                    ordersData = mutableListOf()
                    ordersData = mutableListOf()
                    for (i in 0 until data.length()) {
                        val order = Order(data.getJSONObject(i))
                        if (order.isWinner == 1 && order.isDeleted == 0) {
                            val orderBets = mutableListOf<BetCountEntity>()
                            val betsData = data.getJSONObject(i).getJSONArray("bet_numbers")
                            for (j in 0 until betsData.length()) {
                                val bet = BetCountEntity()
                                val betData = betsData.getJSONObject(j)
                                bet.num =
                                    betData.getString("bet_number").replace("P", "").trim().toInt()
                                bet.money = betData.getDouble("bet_money")
                                bet.pool = betData.getInt("is_pool") == 1
                                bet.type =
                                    betData.getString("bet_number").replace("P", "").trim().length
                                bet.belongTo = data.getJSONObject(i).getString("belong_to")
                                bet.isWinner = betData.getInt("is_winner")
                                bet.rank = betData.getInt("rank")
                                bet.prizes = betData.getDouble("prizes")
                                orderBets.add(bet)
                            }
                            order.bets.addAll(orderBets)
                            ordersData.add(order)
                        }

                    }
                    ordersData.reverse()
                    adapter.replaceData(ordersData)
//                    for (i in 0 until data.length()) {
//                        val order = Order(data.getJSONObject(data.length() - 1 - i))
//
//                        if (order.isWinner == 1 && order.isDeleted == 0) {
//                            val orderBets = mutableListOf<BetCountEntity>()
//                            val betsData = data.getJSONObject(data.length() - 1 - i)
//                                    .getJSONArray("bet_numbers")
//                            for (j in 0 until betsData.length()) {
//                                val bet = BetCountEntity()
//                                val betData = betsData.getJSONObject(j)
//                                bet.num =
//                                        betData.getString("bet_number").replace("P", "").trim().toInt()
//                                bet.money = betData.getDouble("bet_money")
//                                bet.pool = betData.getInt("is_pool") == 1
//                                bet.type =
//                                        betData.getString("bet_number").replace("P", "").trim().length
//                                if (bet.type == 1) {
//                                    bet.type = 2
//                                }
//                                bet.belongTo = data.getJSONObject(i).getString("belong_to")
//                                bet.isWinner = betData.getInt("is_winner")
//                                bet.rank = betData.getInt("rank")
//                                bet.prizes = betData.getDouble("prizes")
//                                orderBets.add(bet)
//                            }
//
//                            order.bets.addAll(orderBets)
//                            ordersData.add(order)
//                        }
//                    }
//
//                    adapter.replaceData(ordersData)
                }

            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }, { error -> error.printStackTrace() })

        requestQueue?.add(request)
    }

    private fun loadOrderByNumer(number: String) {
//        val requestQueue = Volley.newRequestQueue(this)
//
//        val url = Constants.SERVER_URL + "getOrderBySerialNumber"
//        val params = JSONObject()
//        params.put("machine_number", SPUtils[this, "username", ""])
//        params.put("serial_number", number)

        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(false)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()
        RequestCenter.appGetOrders(SPUtils[this, "username", ""] as String, number, null, null, null, object : OkHttpRequestCallback {
            override fun onSuccess(result: String?) {
                try {
                    hud.dismiss()
                    if (JSONObject(result).getJSONArray("data").length() < 1) {
                        ToastUtil.showTipsNotFound(this@RedeemActivity)
                        return
                    }
                    val data = JSONObject(result).getJSONArray("data")[0] as JSONObject
                    val orderBets = mutableListOf<BetCountEntity>()
                    val betsData = data.getJSONArray("bet_numbers")
                    val order = Order(data)
                    for (j in 0 until betsData.length()) {
                        val bet = BetCountEntity()
                        val betData = betsData.getJSONObject(j)
                        bet.num =
                            betData.getString("bet_number").replace("P", "").trim().toInt()
                        bet.money = betData.getDouble("bet_money")
                        bet.pool = betData.getInt("is_pool") == 1
                        bet.type =
                            betData.getString("bet_number").replace("P", "").trim().length
                        bet.belongTo = data.getString("belong_to")
                        bet.isWinner = betData.getInt("is_winner")
                        bet.rank = betData.getInt("rank")
                        bet.prizes = betData.getDouble("prizes")
                        orderBets.add(bet)
                    }
                    order.bets.addAll(orderBets)
                    selectedOrder = order
                    if (selectedOrder != null) {
                        val intent = Intent(this@RedeemActivity, OrderDetailActivity::class.java)
                        intent.putExtra("from", 1)
                        startActivity(intent)
                    } else {
                        ToastUtil.showTipsNotFound(this@RedeemActivity)
                    }
                } catch (e: JSONException) {
                    hud.dismiss()
                    e.printStackTrace()
                }
            }

            override fun onFailure(error: String?) {
                hud.dismiss()
                TLog.net("getOrders failure:$error")
            }
        })


//        val request = JsonObjectRequest(Request.Method.POST, url, params, { response ->
//            try {
//                hud.dismiss()
//                val status = response.get("status") as Int
//                if (status == 200 && !response.isNull("data")) {
//                    val data = response.get("data") as JSONObject
//                    val orderBets = mutableListOf<BetCountEntity>()
//                    val betsData = data.getJSONArray("bet_numbers")
//                    val order = Order(data)
//                    for (j in 0 until betsData.length()) {
//                        val bet = BetCountEntity()
//                        val betData = betsData.getJSONObject(j)
//                        bet.num =
//                            betData.getString("bet_number").replace("P", "").trim().toInt()
//                        bet.money = betData.getDouble("bet_money")
//                        bet.pool = betData.getInt("is_pool") == 1
//                        bet.type =
//                            betData.getString("bet_number").replace("P", "").trim().length
//                        bet.belongTo = data.getString("belong_to")
//                        bet.isWinner = betData.getInt("is_winner")
//                        bet.rank = betData.getInt("rank")
//                        bet.prizes = betData.getDouble("prizes")
//                        orderBets.add(bet)
//                    }
//                    order.bets.addAll(orderBets)
//                    selectedOrder = order
//                    if (selectedOrder != null) {
//                        val intent = Intent(this, OrderDetailActivity::class.java)
//                        intent.putExtra("from", 1)
//                        startActivity(intent)
//                    } else {
//                        ToastUtil.showTipsNotFound(this)
//                    }
//
//                } else {
//                    ToastUtil.showTipsNotFound(this)
//                }
//            } catch (e: JSONException) {
//                hud.dismiss()
//                e.printStackTrace()
//            }
//        }, { error ->
//            hud.dismiss()
//            error.printStackTrace()
//        })
//
//        requestQueue.add(request)
    }

    private fun queryData(str: String) {
        val find = if (str.isEmpty()) {
            ordersData
        } else {
            ordersData.filter { it ->
                it.serialNumber.contains(str)
            }
        }

        adapter.replaceData(find)
    }
}